package part3;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * J5Ex12SortStrings 
 *   Example of use of Collections.sort for Programmer-defined objects
 *   
 * @author tony
 */

class B {
	private int id;
	private String name;
	public B(){ id = 0; name = "None"; }
	public B(int i, String n){ id = i; name = n; }
	public int getID(){ return id; }
	public String getName(){ return name; }
	public String toString(){ return id + ", " + name; }
}
class BCompareByName implements Comparator<B>{
	/**
	 * BCompareByName - compare by name first and then ID
	 */
	public int compare(B o1, B o2) {
		int result = o1.getName().compareTo( o2.getName() );
		return (result != 0) ? result : o1.getID() - o2.getID();
	}
}
class BCompareByID implements Comparator<B>{
	/**
	 * BCompareByID - compare by ID first and then name
	 */
	public int compare(B o1, B o2) {
		int result = o1.getID() - o2.getID();
		return (result != 0) ? result : o1.getName().compareTo( o2.getName() );
	}
}

public class J5Ex14Comparator {

	public static void main(String[] args){
		List<B> list = new ArrayList<B>();
		list.add(new B( 90, "Steps") );
		list.add(new B( 8000, "Hello") );
		list.add(new B( 90, "Good" ) );
		list.add(new B( -10,  "Hello"  ) );

		/*
		 * Iterator for loop
		 */
		for (Iterator<B> i = list.iterator(); i.hasNext(); )
			System.out.println( i.next() );

		System.out.println( "\n\nAnd sorted by name first:");
		Collections.sort( list,  new BCompareByName() );

		for (B b : list)
			System.out.println( b );

		System.out.println( "\n\nAnd sorted by ID first:");
		Collections.sort( list,  new BCompareByID() );

		for (B b : list)
			System.out.println( b );
	}
}
